package com.ybkj.daijia.server.scheduler;

import com.ybkj.daijia.ServiceSetting;
import com.ybkj.daijia.serverUtils.ServiceUtil;
import com.ybkj.daijia.Setting;
import com.ybkj.daijia.serverUtils.SettingUtils;
import com.ybkj.daijia.server.model.Driver;
import com.ybkj.daijia.server.service.DriverService;
import com.ybkj.daijia.server.service.FreightService;
import com.ybkj.daijia.server.service.OrderService;
import com.ybkj.daijia.server.service.OrderStatusService;
import com.ybkj.daijia.server.service.ZhuanxianService;
import java.io.IOException;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.event.ApplicationEventMulticaster;
import org.springframework.core.task.TaskExecutor;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

/**
 * @author FZH
 */
@Component
public class AutoRevoke {

    private static final Logger logger = LoggerFactory.getLogger(AutoRevoke.class);

    @Autowired
    private OrderService orderService;
    @Autowired
    private FreightService freightService;
    @Autowired
    private ZhuanxianService zhuanxianService;
    @Autowired
    private DriverService driverService;
    @Autowired
    private OrderStatusService orderStatusService;
    @Autowired
    private SettingUtils settingUtils;
    @Autowired
    private TaskExecutor taskExecutor;
    @Autowired
    private ApplicationEventMulticaster applicationEventMulticaster;

    public void checkRevoke() throws IOException {

        if (!ThreadControl.AutoRevokeRunning) {

            try {

                ThreadControl.AutoRevokeRunning = true;

                logger.debug("开始检查自动收回订单");

                Setting setting = settingUtils.get();

                Date now = new Date();

                ServiceSetting serviceSetting = ServiceUtil.checkOpen();

//				if(serviceSetting.isDaijia()){
//					try {
//						List<Order> waitRevokeList=orderService.findByStatus(Order.ORDER_STATUS_YIPAIDAN);
//						
//						if(!CollectionUtils.isEmpty(waitRevokeList)){
//							for (Order order : waitRevokeList) {
//								order.setOrderStatuss(orderStatusService.findByOrder(order.getId()));
//								if(!Order.ORDER_TYPE_BUDAN.equals(order.getOrderType())){
//									Date paidanTime=null;
//									List<OrderStatus> orderStatuss=order.getOrderStatuss();
//									if(!CollectionUtils.isEmpty(orderStatuss)){
//										for (int i=(orderStatuss.size()-1);i>=0;i--) {
//											if(orderStatuss.get(i).getStatusType().equals(StatusType.paidan)){
//												paidanTime=orderStatuss.get(i).getHappened();
//												break;
//											}
//										}
//									}
//									if(null!=paidanTime){
//										
//										Calendar calendar=Calendar.getInstance();
//										calendar.setTime(paidanTime);
//										calendar.add(Calendar.MINUTE, setting.getRevokeTime());
//										
//										Date endTime=calendar.getTime();
//										
//										if(now.getTime()>endTime.getTime()){
//											
//											orderService.revoke(order, "时间逾期，系统自动收回了该订单");
//											
//										}
//									}
//								}
//							}
//						}
//					} catch (Exception e1) {
//						e1.printStackTrace();
//					}
//				}

//				if(serviceSetting.isFreight()){
//					try {
//						List<Order> ferightList=freightService.findByStatus(Order.ORDER_STATUS_PAIDAN);
//						if(!CollectionUtils.isEmpty(ferightList)){
//							for (Order order : ferightList) {
//									Date paidanTime=null;
//									List<OrderStatus> orderStatuss=order.getOrderStatusList();
//									if(!CollectionUtils.isEmpty(orderStatuss)){
//										for (int i=(orderStatuss.size()-1);i>=0;i--) {
//											if(orderStatuss.get(i).getStatus().equals(1)){
//												paidanTime=orderStatuss.get(i).getCreated();
//												break;
//											}
//										}
//									}
//									if(paidanTime==null){
//                                      paidanTime=order.getUpdated();
//                                    }									
//									if(null!=paidanTime){
//										
//										Calendar calendar=Calendar.getInstance();
//										calendar.setTime(paidanTime);
//										calendar.add(Calendar.MINUTE, setting.getRevokeTime());
//										
//										Date endTime=calendar.getTime();
//										if(now.getTime()>endTime.getTime()){
//											
//											freightService.revoke(order, "时间逾期，系统自动收回了该订单");
//											
//										}
//									}
//								//}
//							}
//						}
//					} catch (Exception e1) {
//						e1.printStackTrace();
//					}
//				}

//				if(serviceSetting.isZhuanxian()){
//                  try {
//                      List<Order> zhuanxianList=zhuanxianService.findByStatus(Order.ORDER_STATUS_PAIDAN);
//                      if(!CollectionUtils.isEmpty(zhuanxianList)){
//                          for (Order order : zhuanxianList) {
//                                  Date paidanTime=null;
//                                  List<OrderStatus> orderStatuss=order.getStatusList();
//                                  if(!CollectionUtils.isEmpty(orderStatuss)){
//                                      for (int i=(orderStatuss.size()-1);i>=0;i--) {
//                                          if(orderStatuss.get(i).getStatus().equals(1)){
//                                              paidanTime=orderStatuss.get(i).getCreated();
//                                              break;
//                                          }
//                                      }
//                                  }
//                                  if(paidanTime==null){
//                                    paidanTime=order.getUpdated();
//                                  }                                   
//                                  if(null!=paidanTime){
//                                      
//                                      Calendar calendar=Calendar.getInstance();
//                                      calendar.setTime(paidanTime);
//                                      calendar.add(Calendar.MINUTE, setting.getRevokeTime());
//                                      
//                                      Date endTime=calendar.getTime();
//                                      if(now.getTime()>endTime.getTime()){
//                                          
//                                         zhuanxianService.revoke(order, "时间逾期，系统自动收回了该订单");
//                                          
//                                      }
//                                  }
//                              //}
//                          }
//                      }
//                  } catch (Exception e1) {
//                      e1.printStackTrace();
//                  }
//                }

                logger.debug("开始检查自动下线服务人员");

                int autoOfflineTime = setting.getAutoOfflineTime();

                if (autoOfflineTime > 0) {

                    try {
                        List<Driver> offDrivers = driverService
                            .selectByStatus(Driver.DRIVER_ONLINE);

                        if (!CollectionUtils.isEmpty(offDrivers)) {
                            for (Driver driver : offDrivers) {
                                Date posTime = driver.getPosUpdated();
//								Date dutyTime=driver.getDutyTime();
//								if(null!=posTime && StringUtils.isNotBlank(driver.getUserID())){
                                if (null != posTime) {

                                    Calendar calendar = Calendar.getInstance();
                                    calendar.setTime(posTime);
                                    calendar.add(Calendar.MINUTE, autoOfflineTime);
                                    Date lastTime = calendar.getTime();

                                    if (now.getTime() > lastTime.getTime()) {//更新时间超时

//										Date lastTime2=null;
//										if(null!=dutyTime){
//											Calendar calendar2=Calendar.getInstance();
//											calendar2.setTime(dutyTime);
//											calendar2.add(Calendar.MINUTE, 3);
//											lastTime2=calendar2.getTime();
//										}

//										if(null==lastTime2 || now.getTime()>lastTime2.getTime()){//上线时间超时

//											boolean getuiOnline=false;
//											if(StringUtils.isNotBlank(driver.getUserID())){
//												getuiOnline=GeTuiEmployV4.getClientOnline(driver.getUserID(), settingUtils.get());
//											}
//											
//											if(!getuiOnline){//推送非在线

                                        driverService
                                            .updateStatus(Driver.DRIVER_OFFLINE, driver.getId());

//												DriverAutoOfflineEvent driverAutoOfflineEvent = new DriverAutoOfflineEvent(driver);
//												applicationEventMulticaster.multicastEvent(driverAutoOfflineEvent);

//											}
//											else{
//												try {

                                        //发送设备推送
//													PushDataV4 pushDataV4 = new PushDataV4();
//													pushDataV4.setCode("0X08");
//													Map<String, String> extra=new HashMap<String, String>();
//													extra.put("content", "更新位置");
//													pushDataV4.setExtra(extra);
//													
//													GeTuiEmployV4.push(driver, pushDataV4 ,settingUtils.get());
//													
//												} catch (IOException e) {
//													logger.debug("push error : " + e.getMessage());
//												}
//											}

//										}

                                    }

                                }
                            }
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }

                if (serviceSetting.isDaijia()) {
//					logger.debug("开始检查预派单订单");

//					try {
//						List<Order> yupaidanlist=orderService.findByStatus(Order.ORDER_STATUS_YUPAIDAN);
//						if(!CollectionUtils.isEmpty(yupaidanlist)){
//							
//							Collections.sort(yupaidanlist, new Comparator<Order>() {
//						        public int compare(Order arg0, Order arg1) {
//						            return arg0.getServerTime().compareTo(arg1.getServerTime());
//						        }
//						    });
//							
//							for (Order order : yupaidanlist) {
//								Driver driver=driverMapper.selectByPrimaryKey(order.getDriverId());
//								if(null!=driver && driver.getStatus().equals(Driver.DRIVER_ONLINE)){
//									orderService.yupaidan(driver, order, "auto");
//									
//									//派单事件
//									OrderPaidanEvent paidanEvent = new OrderPaidanEvent(order);
//									applicationEventMulticaster.multicastEvent(paidanEvent);
//									
//								}
//							}
//						}
//					} catch (Exception e) {
//						e.printStackTrace();
//					}
                }


            } finally {
                ThreadControl.AutoRevokeRunning = false;
            }

        }

    }
}
